import 'package:flutter/material.dart';
import 'dart:math';

class AudioWaveform extends StatefulWidget {
  final List<double> amplitudes; // 音频振幅数据列表
  final int waveCount; // 波形数量
  final double height; // 组件高度
  final double width; // 组件宽度
  final Color waveColor; // 波形颜色
  final double maxAmplitude; // 最大振幅值
  final Duration animationDuration; // 动画持续时间
  final Curve animationCurve; // 动画曲线

  const AudioWaveform({
    Key? key,
    this.amplitudes = const [],
    this.waveCount = 50,
    this.height = 100.0,
    this.width = double.infinity,
    this.waveColor = Colors.blue,
    this.maxAmplitude = 32767.0, // 16位PCM的最大值
    this.animationDuration = const Duration(milliseconds: 150),
    this.animationCurve = Curves.easeOutCubic,
  }) : super(key: key);

  @override
  State<AudioWaveform> createState() => _AudioWaveformState();
}

class _AudioWaveformState extends State<AudioWaveform> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late List<double> _displayedAmplitudes;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: widget.animationDuration,
    )..repeat();
    _displayedAmplitudes = List.filled(widget.waveCount, 0.0);
    _updateAmplitudes();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant AudioWaveform oldWidget) {
    super.didUpdateWidget(oldWidget);
    /*if (oldWidget.amplitudes != widget.amplitudes) {
            _updateAmplitudes();
    }*/
    _updateAmplitudes();
  }

  // 更新显示的振幅值并触发动画
  void _updateAmplitudes() {
    final List<double> normalizedAmplitudes = _normalizeAmplitudes();
    // 如果没有新数据，使用随机值创建一个"呼吸"效果
    if (normalizedAmplitudes.isEmpty) {
      setState(() {
        _displayedAmplitudes = List.generate(
            widget.waveCount,
                (index) => Random().nextDouble() * 0.1
        );
      });
      return;
    }

    // 动画更新波形
    // _animationController.forward(from: 1);

    setState(() {
      // 平滑过渡到新的振幅值
      _displayedAmplitudes = normalizedAmplitudes;
      //print('_displayedAmplitudes ====> ${_displayedAmplitudes}');
    });
  }

  // 归一化振幅数据，使其在0.0到1.0之间
  List<double> _normalizeAmplitudes() {
    if (widget.amplitudes.isEmpty) return [];

    // 复制并截断或填充振幅数据以匹配waveCount
    final List<double> normalized = List.filled(widget.waveCount, 0.0);

    for (int i = 0; i < min(widget.amplitudes.length, widget.waveCount); i++) {
      // 将振幅归一化到0.0-1.0范围
      double value = widget.amplitudes[i] / widget.maxAmplitude;
      // 限制最大值，避免过高的波形
      normalized[i] = min(1.0, max(0.0, value));
    }

    return normalized;
  }

  @override
  Widget build(BuildContext context) {
   // print('_displayedAmplitudes :: ${_displayedAmplitudes}');
    return Container(
      width: widget.width,
      height: widget.height,
      child: CustomPaint(
        painter: WaveformPainter(
          amplitudes: _displayedAmplitudes,
          color: widget.waveColor,
          animationValue: _animationController.value,
          animationCurve: widget.animationCurve,
        ),
      ),
    );
  }
}

// 波形绘制器
class WaveformPainter extends CustomPainter {
  final List<double> amplitudes;
  final Color color;
  final double animationValue;
  final Curve animationCurve;

  WaveformPainter({
    required this.amplitudes,
    required this.color,
    required this.animationValue,
    required this.animationCurve,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // print('WaveformPainter amplitudes :: animationValue: ${animationValue}, ');
    if (amplitudes.isEmpty) return;

    final double waveWidth = size.width / amplitudes.length;
    final double centerY = size.height / 2;

    // 应用动画曲线
    final double animatedValue = animationCurve.transform(animationValue);

    final Paint paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    // 绘制每个波形条
    for (int i = 0; i < amplitudes.length; i++) {
      // 计算当前波形条的高度（应用动画值）
      final double height = amplitudes[i] * size.height * animatedValue;
      final double halfHeight = height / 2;

      // print('波形条 animation height: ${height}');

      // 计算波形条的位置
      final double x = i * waveWidth;
      final double left = x + (waveWidth * 0.2); // 留一点间距
      final double right = x + (waveWidth * 0.8);
      final double top = centerY - halfHeight;
      final double bottom = centerY + halfHeight;

      // 绘制圆角矩形
      final RRect rrect = RRect.fromLTRBR(
        left, top, right, bottom,
        Radius.circular(waveWidth * 0.3),
      );
      canvas.drawRRect(rrect, paint);
    }
  }

  @override
  bool shouldRepaint(covariant WaveformPainter oldDelegate) {
    return oldDelegate.amplitudes != amplitudes ||
        oldDelegate.animationValue != animationValue;
  }
}